package com.fxsh.learn.websocket;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 服务器
 * @ClassName: WebSocket
 * @Description: TODO
 * @author OnlyMate
 * @Date 2018年8月16日 下午2:46:54
 *
 */
@Slf4j
@ServerEndpoint("/ws/test")
@Component
public class WebSocket {
//	private static int onlineCount = 0;
//	private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
	private Session session;

	@OnOpen
	public void onOpen(Session session) throws IOException {

		this.session = session;

//		addOnlineCount();
//		clients.put(session.getId(), this);
//		System.out.println("已连接");
		log.info("已连接");
		sendMessageTo("Hello",null);
	}

	@OnClose
	public void onClose() throws IOException {
//		clients.remove(session);
//		subOnlineCount();
		log.info("已关闭");
	}

//	@OnMessage
//	public void onMessage(String message) throws IOException {
//		JSONObject jsonTo = JSONObject.parseObject(message);
//		System.out.println(jsonTo.getString("to") +":"+ jsonTo.getString("msg"));
//
//		if (!jsonTo.getString("to").toLowerCase().equals("all")){
//			sendMessageTo(jsonTo.getString("msg"), jsonTo.getString("to"));
//		}else{
//			sendMessageAll(jsonTo.getString("msg"));
//		}
//	}

	@OnError
	public void onError(Session session, Throwable error) {
		log.info(error.getMessage());
		error.printStackTrace();
	}

	public void sendMessageTo(String message, String To) throws IOException {
		 session.getBasicRemote().sendText(message);
//		session.getAsyncRemote().sendText(message);
	}

//	public void sendMessageAll(String message) throws IOException {
//		for (WebSocket item : clients.values()) {
//			item.session.getAsyncRemote().sendText(message);
//		}
//	}

}